/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.manage.order;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.manage.entrepot.EntrepotService;
import shop.services.manage.entrepot.bean.Entrepot;
import shop.services.manage.order.OrderService;
import shop.services.manage.order.bean.Order;
import shop.services.manage.orderdetail.OrderdetailService;
import shop.services.manage.orderdetail.bean.Orderdetail;
import shop.services.manage.product.ProductService;
import shop.services.manage.product.bean.Product;
import shop.services.manage.rank.RankService;
import shop.services.manage.rank.bean.Rank;
import shop.services.manage.record.RecordService;
import shop.services.manage.record.bean.Record;
import shop.services.manage.spec.SpecService;
import shop.services.manage.spec.bean.Spec;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：OrderAction
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:48:44
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/order/")
public class OrderAction extends BaseController<Order> {
    private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);
    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;
    @Autowired
    private RankService rankService;
    @Autowired
    private EntrepotService entrepotService;
    @Autowired
    private SpecService specService;
    @Autowired
    private ProductService productService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private OrderdetailService orderdetailService;
    private static final String page_toList = "/manage/order/orderList";
    private static final String page_toEdit = "/manage/order/orderEdit";
    private static final String page_toStoreOrder = "/manage/order/sellerOrder";
    private static final String page_toStoreOrderDetail = "/manage/order/sellerOrderDetail";

    public OrderService getService() {
        return orderService;
    }

    private OrderAction() {
        super.page_toList = page_toList;
        super.page_toAdd = null;
        super.page_toEdit = page_toEdit;
    }

    /**
     * 跳转到分销订单列表页面
     *
     * @return
     */
    @RequestMapping("toStoreOrder")
    public String toStoreOrder() {
        return page_toStoreOrder;
    }

    /**
     * 跳转到分销订单详情页面
     *
     * @return
     */
    @RequestMapping("toStoreOrderDetail")
    public String toStoreOrderDetail(@ModelAttribute("e") Order order, ModelMap model) throws Exception {
        order = orderService.selectOne(order);
        model.addAttribute("e", order);
        return page_toStoreOrderDetail;
    }

    /**
     * 跳转到订单详情页面
     */
    @RequestMapping(value = "toEditOrder")
    public String toEditOrder(String id, ModelMap model) throws Exception {
        Orderdetail e = orderdetailService.selectById(id);
        switch (e.getStatus()) {
            case "init":
                e.setStatus("待付款");
                break;
            case "pass":
                e.setStatus("待发货");
                break;
            case "send":
                e.setStatus("已发货");
                break;
            case "finish":
                e.setStatus("已完成");
                break;
            default:
                e.setStatus("已关闭");
        }
        model.addAttribute("e", e);
        return page_toEdit;
    }

    /**
     * 订单商品发货处理
     *
     * @param e
     * @return
     */
    @RequestMapping("sendProduct")
    public String sendProduct(Order e) {
        //确认收货
        if (e.getStatus().equals("已发货")) {
            e.setStatus("finish");
            orderService.update(e);
            //确认收货消息通知
            Order order = new Order();
            order = orderService.selectOne(order);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(order.getId());
            List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
            orderdetail.setId(orderdetailList.get(0).getId());
            orderdetail = orderdetailService.selectOne(orderdetail);
            User user = new User();
            user.setId(order.getUserID());
            user = userService.selectOne(user);
            Map<String, String> msgParam = new HashMap<>();
            msgParam.put("first", "亲爱的" + order.getNickname() + "，您有一个订单状态变更为已完成");
            msgParam.put("keyword1", order.getId());
            msgParam.put("keyword2", order.getCreateTime());
            msgParam.put("remark", "点击查看订单详情");
            if ("y".equals(user.getOrderFinishStatus()))
                WxMsgUtil.sendSubOrderFinishMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
            if (!"0".equals(user.getPid())) {
                User supUser = new User();
                supUser.setId(user.getPid());
                supUser = userService.selectOne(supUser);
                Map<String, String> msgParam2 = new HashMap<>();
                msgParam2.put("first", "亲爱的" + order.getNickname() + "，您有一个分销订单状态变更为已完成");
                msgParam2.put("keyword1", order.getId());
                msgParam2.put("keyword2", orderdetail.getProductName());
                msgParam2.put("keyword3", order.getCreateTime());
                msgParam.put("remark", "点击查看订单详情");
                if ("y".equals(supUser.getOrderSubFinishStatus()))
                    WxMsgUtil.sendOrderFinishMsg(msgParam, systemManager.getAccessToken(), supUser.getOpenID());
            }
        }
        //商品发货
        if (e.getStatus().equals("待发货")) {
            e.setStatus("send");
            orderService.update(e);
            //订单发货消息通知
            Order order = new Order();
            order.setId(e.getId());
            order = orderService.selectOne(order);
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOrderID(order.getId());
            List<Orderdetail> orderdetailList = orderdetailService.selectList(orderdetail);
            orderdetail.setId(orderdetailList.get(0).getId());
            orderdetail = orderdetailService.selectOne(orderdetail);
            User user = new User();
            user.setId(order.getUserID());
            user = userService.selectOne(user);
            Map<String, String> msgParam = new HashMap<>();
            msgParam.put("first", "亲爱的" + order.getNickname() + "，您的订单已经发货了，请耐心等待哦~");
            msgParam.put("keyword1", orderdetail.getProductName());
            msgParam.put("keyword2", order.getExpressCompany());
            msgParam.put("keyword3", order.getExpressNum());
            msgParam.put("keyword4", order.getAddressArea() + order.getAddressDetail());
            msgParam.put("keyword5", "--");
            msgParam.put("remark", "点击查看订单详情");
            if ("y".equals(user.getOrderSendStatus()))
                WxMsgUtil.sendProductMsg(msgParam, systemManager.getAccessToken(), user.getOpenID());
        }
        return page_toList;
    }

    /**
     * 批量删除订单及对应的订单详情
     *
     * @param orderIDs
     * @return
     */
    @RequestMapping(value = "deletesOrderDetail", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deletesOrderDetail(@RequestParam(value = "orderIDs[]") String[] orderIDs) {
        JSONResult jsonResult = new JSONResult();
        Orderdetail orderdetail = new Orderdetail();
        if (orderIDs == null || orderIDs.length == 0) {
            throw new NullPointerException("请选择需要删除订单！");
        } else {
            Order order = new Order();
            for (int i = 0; i < orderIDs.length; i++) {
                orderdetail.setOrderID(orderIDs[i]);
                List<Orderdetail> orderdetails = orderdetailService.selectList(orderdetail);
                for (Orderdetail orderdetailOne : orderdetails) {
                    orderdetailService.delete(orderdetailOne);
                }
                order.setId(orderIDs[i]);
                orderService.delete(order);
            }
            jsonResult.setSuccess(true);
        }
        return jsonResult;
    }

    /**
     * 批量删除订单及对应的订单详情
     */
    @RequestMapping(value = "deleteOne", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteOne(String orderID) {
        JSONResult jsonResult = new JSONResult();
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(orderID);
        /*删除该订单所有的订单详情*/
        List<Orderdetail> orderdetails = orderdetailService.selectList(orderdetail);
        for (Orderdetail orderdetailOne : orderdetails) {
            orderdetailService.delete(orderdetailOne);
        }
        Order order = new Order();
        order.setId(orderID);
        orderService.delete(order);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 订单详情商品列表
     */
    @RequestMapping("loadProduct")
    @ResponseBody
    public PagerModel loadProduct(HttpServletRequest request, Orderdetail e) {
        int offset = 0;
        int pageSize = 10;
        if (request.getParameter("start") != null) {
            offset = Integer.parseInt(request.getParameter("start"));
        }
        if (request.getParameter("length") != null) {
            pageSize = Integer.parseInt(request.getParameter("length"));
        }
        if (offset < 0)
            offset = 0;
        if (pageSize < 0) {
            pageSize = 10;
        }
        e.setOffset(offset);
        e.setPageSize(pageSize);
        PagerModel pager = orderdetailService.selectPageListProduct(e);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 线下购买会员审核方法(线下支付)
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "updateCheckStatus", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateCheckStatus(HttpServletRequest request, @ModelAttribute("e") Order order) throws Exception {
        jsonResult = new JSONResult();
        //更新订单状态
        orderService.update(order);
        //更新用户数据
        User user = new User();
        user.setId(order.getUserID());
        user = userService.selectOne(user);
        if ("0".equals(user.getPid())) {
            //更新平台商品库存
            Spec spec = new Spec();
            spec.setProductID(order.getProductID());
            spec.setSpecCombination(order.getSpecInfo());
            spec = specService.selectOne(spec);
            spec.setSpecStock(spec.getSpecStock() - order.getNumber());
            specService.update(spec);
            //更新平台商品销售量
            Product product = new Product();
            product.setId(order.getProductID());
            product = productService.selectOne(product);
            product.setSellcount(product.getSellcount() + order.getNumber());
            productService.update(product);
        } else {
            //更新上级仓库库存
            Entrepot supEntrepot = new Entrepot();
            supEntrepot.setUserID(user.getPid());
            supEntrepot.setProductID(order.getProductID());
            supEntrepot.setSpecInfo(order.getSpecInfo());
            supEntrepot = entrepotService.selectOne(supEntrepot);
            supEntrepot.setNumber(supEntrepot.getNumber() - order.getNumber());
            entrepotService.update(supEntrepot);
            //上级返利
            User supUser = new User();
            supUser.setId(user.getPid());
            supUser = userService.selectOne(supUser);
            supUser.setWalletMoney(supUser.getWalletMoney().add(order.getPtotal()));
            supUser.setScore(supUser.getScore().add(order.getPtotal()));//更新上级积分
            userService.update(supUser);
            //生成交易记录（上级钱包）
            Record record = new Record();
            record.setUserID(supUser.getId());
            record.setTransType(order.getTransType());
            record.setTransID(order.getId());
            record.setMoney(order.getPtotal());
            recordService.insert(record);
        }
        Rank rank = new Rank();
        rank.setType(order.getRankType());
        rank = rankService.selectOne(rank);
        user.setRankID(rank.getId());
        user.setRid("2");
        user.setPid("0");
        userService.update(user);
        //解除绑定的下级
        User subUser = new User();
        subUser.setPid(user.getId());
        List<User> subUserList = userService.selectList(subUser);
        if (subUserList.size() != 0 && subUserList != null) {
            for (User userInfo : subUserList) {
                userInfo.setPid("");
                userService.update(userInfo);
            }
        }
        //创建分销仓库项
        Entrepot entrepot = new Entrepot();
        entrepot.setUserID(order.getUserID());
        entrepot.setProductID(order.getProductID());
        entrepot.setSpecInfo(order.getSpecInfo());
        entrepot = entrepotService.selectOne(entrepot);
        if (entrepot == null) {
            Entrepot entrepotInfo = new Entrepot();
            entrepotInfo.setUserID(order.getUserID());
            entrepotInfo.setProductID(order.getProductID());
            entrepotInfo.setSpecInfo(order.getSpecInfo());
            entrepotInfo.setPrice(order.getPrice());
            entrepotInfo.setNumber(order.getNumber());
            entrepotInfo.setOrderID(order.getId());
            entrepotService.insert(entrepotInfo);//插入分销仓库表
        } else {
            entrepot.setNumber(entrepot.getNumber() + order.getNumber());
            entrepotService.update(entrepot);//更新分销仓库表
        }
        return jsonResult;
    }

    /**
     * 查询分销订单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectStoreOrder")
    @ResponseBody
    public JSONResult selectStoreOrder(Order order) throws Exception {
        List<Order> orderList = orderService.selectStoreOrder(order);
        for (Order orderInfo : orderList) {
            User user = new User();
            user.setId(orderInfo.getUserID());
            user = userService.selectOne(user);
            User supUser = new User();
            supUser.setId(orderInfo.getPid());
            supUser = userService.selectOne(supUser);
            if (user != null)
                orderInfo.setNickname(user.getNickname());
            if (supUser != null)
                orderInfo.setPnickname(supUser.getNickname());
        }
        jsonResult = new JSONResult();
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 查询购买会员类型的订单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectRankOrder")
    @ResponseBody
    public JSONResult selectRankOrder(Order order) throws Exception {
        List<Order> orderList = orderService.selectRankOrder(order);
        jsonResult = new JSONResult();
        jsonResult.setData(orderList);
        return jsonResult;
    }

    /**
     * 查询购买会员类型订单的详情
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectRankOrderDetail")
    @ResponseBody
    public JSONResult selectRankOrderDetail(Order order) throws Exception {
        order = orderService.selectOne(order);
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setOrderID(order.getId());
        orderdetail = orderdetailService.selectOne(orderdetail);
        order.setProductName(orderdetail.getProductName());
        order.setNumber(orderdetail.getNumber());
        order.setSpecInfo(orderdetail.getSpecInfo());
        jsonResult = new JSONResult();
        jsonResult.setData(order);
        return jsonResult;
    }

}
